package com.seeyon.ctp.rest.resources;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.seeyon.apps.reimburseplugin.listener.ReimburseListener;
import com.seeyon.apps.reimburseplugin.util.YRUtil;
import com.seeyon.apps.reimburseplugin.util.YrHttpUtils;
import com.seeyon.cap4.form.service.CAP4FormManager;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.affair.manager.AffairManager;
import com.seeyon.ctp.common.ctpenumnew.CtpEnumUtil;
import com.seeyon.ctp.common.exceptions.BusinessException;
import com.seeyon.ctp.common.filemanager.dao.AttachmentDAO;
import com.seeyon.ctp.common.filemanager.manager.AttachmentManager;
import com.seeyon.ctp.common.po.ctpenumnew.CtpEnumItem;
import com.seeyon.ctp.common.po.ctpenumnew.CtpEnumItemPO;
import com.seeyon.ctp.common.po.filemanager.Attachment;
import com.seeyon.ctp.organization.bo.V3xOrgDepartment;
import com.seeyon.ctp.organization.bo.V3xOrgMember;
import com.seeyon.ctp.organization.bo.V3xOrgPost;
import com.seeyon.ctp.organization.manager.OrgManager;
import com.seeyon.ctp.util.DBAgent;
import com.seeyon.ctp.util.Strings;
import com.seeyon.ctp.util.annotation.RestInterfaceAnnotation;
import com.seeyon.ctp.util.json.JSONUtil;
import com.seeyon.v3x.dee.common.base.util.DateUtils;

@Path("reimburse")
@Consumes({"application/json", "application/xml"})
@Produces({"application/json"})
public class ReimburseReoucrce extends BaseResource{
	private static final Log logger=LogFactory.getLog(ReimburseListener.class);
	private OrgManager orgManager = (OrgManager) AppContext.getBean("orgManager");
	private CAP4FormManager cap4FormManager = (CAP4FormManager) AppContext.getBean("cap4FormManager"); 
	private AffairManager affairManager = (AffairManager) AppContext.getBean("affairManager");
//	private EnumItemDAO newEnumItemDAO = (EnumItemDAO) AppContext.getBean("newEnumItemDAO");
	private AttachmentManager attachmentManager = (AttachmentManager) AppContext.getBean("attachmentManager");
	
	private AttachmentDAO attachmentDAO = (AttachmentDAO) AppContext.getBean("attachmentDAO");
	
	@POST
	@Path("save")
	@Consumes({"application/json"})
	@Produces({"application/json"})
	@RestInterfaceAnnotation
	public Response reimburseSave(String data) throws Exception {
		
		Map<String,Object> resultMap = new HashMap<>();
		try {
			Map<String,Object> dataMap =JSONUtil.parseJSONString(data, Map.class);
			logger.info("=========reimburse==========："+data);
			Map<String,Object> mainMap = new HashMap<String,Object>();
			Map<String,Object> mainData = (Map<String, Object>) dataMap.get("mainData");
			String summaryId  = YRUtil.getString(dataMap.get("summaryId"));
			List<Long> references = new ArrayList<Long>();
			references.add(Long.valueOf(summaryId));
			List<Attachment> attachments = attachmentDAO.getByReference(references);
			if(attachments != null && attachments.size() > 0) {
				StringBuilder sbr=new StringBuilder();
				StringBuilder filenames =new StringBuilder();
//				if (attachments!=null&&attachments.size()>0) {
					for(int i=0;i<attachments.size();i++) {
						Attachment attachment=attachments.get(i);
						if(attachment.getMimeType().equals("collaboration")) {
							continue;
						}
						String attName=attachment.getFilename();
						String att=attachment.getFileUrl()+"";
						if (i==0) {
							filenames.append(attName);
							sbr.append(att);
						}else {
							
							filenames.append("|"+attName);
							sbr.append("|"+att);
						}
					}
					mainMap.put("attachmentNum", attachments.size());
					mainMap.put("attachmentName", filenames.toString());
					mainMap.put("attachmentId", sbr.toString());
				}else {
					mainMap.put("attachmentNum",0);
					mainMap.put("attachmentName", "");
					mainMap.put("attachmentId", "");
				}
				
//			}else {
//				mainMap.put("attachmentNum",0);
//				mainMap.put("attachmentName", "");
//				mainMap.put("attachmentId", "");
//			}
			mainData.put("dates", DateUtils.dateToString(new Date(),"yyyy-MM-dd HH:mm:ss"));
			if(mainData.containsKey("startDept")) {
				V3xOrgDepartment department= orgManager.getDepartmentById(Long.valueOf(YRUtil.getString(mainData.get("startDept"))));
				if(department != null) {
					mainData.put("startDept", department.getCode());
					mainData.put("budgetDept", department.getCode());
				}
			}
			String fundsNature = "";
			
			if(mainData.containsKey("fundsNature")) {
				//合并代码-szw
				CtpEnumItem ctpEnumItem = findById(Long.valueOf(YRUtil.getString(mainData.get("fundsNature"))));
				//合并代码-szw
				fundsNature = ctpEnumItem.getShowvalue();
				logger.info("fundsNature===="+fundsNature);
				mainData.put("fundsNature", ctpEnumItem.getShowvalue());
			}
			String userCode = "";
			if(mainData.containsKey("evectionPerson")) {
				logger.info("evectionPerson："+YRUtil.getString(mainData.get("evectionPerson")));
				V3xOrgMember orgMember= orgManager.getMemberById(Long.valueOf(YRUtil.getString(mainData.get("evectionPerson"))));
				if(orgMember != null) {
					logger.info("orgMember != null："+orgMember.getLoginName());
					mainData.put("evectionPerson", orgMember.getLoginName());
					mainData.put("receiver", orgMember.getLoginName());
					mainData.put("operator",orgMember.getLoginName());
					userCode = orgMember.getLoginName();
				}else {
					logger.info("orgMember == null："+YRUtil.getString(mainData.get("evectionPerson")));
				}
			}else {
				mainData.put("evectionPerson", "");
				mainData.put("receiver", "");
				mainData.put("operator", "");
			}
			
			if(mainData.containsKey("post")) {
				V3xOrgPost orgPost= orgManager.getPostById(Long.valueOf(YRUtil.getString(mainData.get("post"))));
				if(orgPost != null) {
					mainData.put("post", orgPost.getName());
				}
			}
			mainMap.put("mainData", mainData);
			
			List<Map<String,Object>> details = (List<Map<String, Object>>) dataMap.get("details");
			String xmCode="";
			String xmName="";
			if(!fundsNature.equals("")) {
				String[] xmArr=fundsNature.split("-");
				xmCode=xmArr[0];
				xmName=xmArr[1];
			}
			if(details != null && details.size() > 0 ) {
				for (Map<String, Object> detail : details) {
//					remark
					String remark = YRUtil.getString(detail.get("remark"));
					if(!remark.equals("")) {
						if(remark.contains(" ")) {
							String[] xmArr=remark.split(" ");
							xmCode=xmArr[0];
							xmName=xmArr[2];
						}
					}
					detail.put("deptId", YRUtil.getString(mainData.get("startDept")));
					detail.put("szxmid", xmCode);
					detail.put("szxmname", xmName);
					detail.put("remark", xmCode);
					detail.put("jkbxr", userCode);
					
				}
			}
			mainMap.put("details", details);
			logger.info("推送json："+JSONUtil.toJSONString(mainMap));
			String url=AppContext.getSystemProperty("reimburseplugin.interfaceUrl");
			String newUrl=url+"?service=comfirm&urid=oa&pwd=oa";
			String result = new YrHttpUtils().httpPost(newUrl, JSONUtil.toJSONString(mainMap));
			logger.info("推送返回信息："+result);
			if(Strings.isNotEmpty(result)) {
				Map<String,Object> mapres = JSONUtil.parseJSONString(result, Map.class); 
				if(YRUtil.getString(mapres.get("code")).equals("1")) {
					resultMap.put("success", 1);
					resultMap.put("message", YRUtil.getString(mapres.get("message")));
				}else {
					resultMap.put("success", -1);
					resultMap.put("message", mapres.get("message"));
				}
			}else {
				resultMap.put("success", -1);
				resultMap.put("message", "推送返回信息为空！");
			}
		} catch (Exception e) {
			logger.error("OA接口调用异常：", e);
			resultMap.put("success", -1);
			resultMap.put("message", e);
		}
		
		
		return this.ok(resultMap);
	}
	
	public CtpEnumItem findById(Long id) throws BusinessException {
		String hql = " select " + CtpEnumUtil.newCtpEnumBeanHql +  "from " + CtpEnumItemPO.class.getName() + " f where f.id=:id";
		Map<String, Long> map = new HashMap<String, Long>();
		map.put("id", id);
		List list = DBAgent.find(hql,map);
		if(CollectionUtils.isNotEmpty(list)){
			return (CtpEnumItem) list.get(0);
		}
		return null;
	}
	
}
